from django.http import JsonResponse

# Create your views here.
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from RouteManage.models import *
from RouteManage.serializers import *


@csrf_exempt
def getRoutes(request):
    if request.method == 'GET':
        id = request.GET.get("id")
        State = request.GET.get("State")
        print(id)
        print(State)
        if id is None:
            routes = Route.objects.filter(State="正常运行")
        elif State is None:
            routes = Route.objects.filter(ManagerID=id)
        else:
            routes = Route.objects.filter(ManagerID=id, State=State)
        # if State is None:
        #     routes = Route.objects.filter(ManagerID=id)
        # else:
        #     routes = Route.objects.filter(ManagerID=id, State=State)
        ans = []
        for route in routes:
            ans.append(route.to_dict())
            print(route.to_dict())
        return JsonResponse({'Routes': ans}, safe=False)


@csrf_exempt
def changeState(request):
    if request.method == 'POST':
        RouteID = request.POST.get('RouteID')
        State = request.POST.get("State")
        print(RouteID)
        print(State)
        data = {}
        try:
            route = Route.objects.get(RouteID=RouteID)
        except Route.DoesNotExist:
            return JsonResponse({'Message': '路线不存在'}, safe=False)
        if State == Route.State:
            return JsonResponse({'Message': '无需修改'}, safe=False)
        if State == '停止运营':
            rotas = Rota.objects.filter(Route=route)
            for rota in rotas:
                rota.delete()
            Reason = request.POST.get("Reason")
            data = {'State': State, 'RouteStopUseReason': Reason, 'RouteStopUseDate': timezone.localdate()}
        elif State == '正常运行':
            data = {'State': State}
        newRoute = RouteSerializer(route, data=data)
        if newRoute.is_valid():
            newRoute.save()
            return JsonResponse({'Message': '修改成功'}, safe=False)
        else:
            print(newRoute.errors)
            return JsonResponse({'Message': '修改失败'}, safe=False)


@csrf_exempt
def addNewRoute(request):
    if request.method == "POST":
        print(request.POST)
        result = Route.objects.filter(RouteID=request.POST.get("RouteID"))
        if result.exists():
            return JsonResponse({'Message': "路线ID重复"}, safe=False)
        route = RouteSerializer(data=request.POST)
        if route.is_valid():
            route.save()
        else:
            print(route.errors)
            return JsonResponse({"Message": "参数不合法"}, safe=False)
        return JsonResponse({"Message": "成功"}, safe=False)


@csrf_exempt
def changeSteps(request):
    if request.method == "POST":
        try:
            route = Route.objects.get(RouteID=request.POST.get("RouteID"))
        except Route.DoesNotExist:
            return JsonResponse({'Message': '路线不存在'}, safe=False)
        print(request.POST)
        route = RouteSerializer(route, request.POST)
        if route.is_valid():
            route.save()
            return JsonResponse({'Message': '修改成功'}, safe=False)
        else:
            print(route.errors)
            return JsonResponse({'Message': '参数不合法'}, safe=False)


@csrf_exempt
def deleteRoute(request):
    if request.method == "POST":
        try:
            route = Route.objects.get(RouteID=request.POST.get("RouteID"))
        except Route.DoesNotExist:
            return JsonResponse({'Message': '路线不存在'}, safe=False)
        route.delete()
        return JsonResponse({'Message': '成功'}, safe=False)


@csrf_exempt
def addRota(request):
    if request.method == "POST":
        data = request.POST.copy()
        del data["CarSendTime"]
        fail = []
        print(request.POST)
        for time in request.POST["CarSendTime"].split(','):
            print(time)
            data["CarSendTime"]=time
            rota = RotaSerializer(data=data)
            if rota.is_valid():
                rota.save()
            else:
                print(rota.errors)
                fail.append(time)
        return JsonResponse({"Fail": fail}, safe=False)


@csrf_exempt
def getRota(request):
    if request.method == "GET":
        driver = request.GET.get("DriverID")
        route = request.GET.get("RouteID")
        rotas = None
        if driver is not None:
            rotas = Rota.objects.filter(Driver=driver)
        elif route is not None:
            rotas = Rota.objects.filter(Route=route)
        rota = []
        if rotas is not None:
            for r in rotas:
                rota.append(r.to_dict())
        return JsonResponse({"Rota": rota}, safe=False)


@csrf_exempt
def deleteRota(request):
    if request.method == "POST":
        rotas = Rota.objects.filter(Car=request.POST.get("Car"),
                                    Driver=request.POST.get("Driver"),
                                    Route=request.POST.get("Route"),
                                    CarSendTime=request.POST.get("CarSendTime"))
        for r in rotas:
            r.delete()
        return JsonResponse({'Message': '成功'}, safe=False)


@csrf_exempt
def modifyRota(request):
    if request.method == "POST":
        try:
            rota = Rota.objects.get(Car=request.POST.get("Car"),
                                    Driver=request.POST.get("Driver"),
                                    Route=request.POST.get("Route"),
                                    CarSendTime=request.POST.get("CarSendTime"))
        except Rota.DoesNotExist:
            return JsonResponse({'Message': '排班记录不存在'}, safe=False)
        repeat = Rota.objects.filter(Car=request.POST.get("Car"),
                                     Driver=request.POST.get("Driver"),
                                     Route=request.POST.get("Route"),
                                     CarSendTime=request.POST.get("NewTime"))
        if repeat:
            return JsonResponse({'Message': '发车时间重复'}, safe=False)
        data = {"CarSendTime": request.POST.get("NewTime")}
        rota = RotaSerializer(rota, data=data)
        if rota.is_valid():
            rota.save()
            return JsonResponse({'Message': '成功'}, safe=False)


@csrf_exempt
def rotaFinish(request):
    if request.method == "POST":
        try:
            rota = Rota.objects.get(Car=request.POST.get("Car"),
                                    Driver=request.POST.get("Driver"),
                                    Route=request.POST.get("Route"),
                                    CarSendTime=request.POST.get("CarSendTime"))
        except Rota.DoesNotExist:
            return JsonResponse({'Message': '排班信息不存在'}, safe=False)
        if rota.Finished:
            return JsonResponse({'Message': '该排班已完成'}, safe=False)
        rota = RotaSerializer(rota, data={"Finished": "True"})
        if rota.is_valid():
            time = timezone.localdate().strftime("%Y-%m-%d") + "T" + request.POST.get("CarSendTime") + ".000000Z"
            data = {'Car': request.POST.get("Car"), 'Driver': request.POST.get("Driver"),
                    'Route': request.POST.get("Route"), "CarSendTime": time}
            data = request.POST.copy()
            data["CarSendDate"] = timezone.localdate().strftime("%Y-%m-%d")
            service = ServiceSerializer(data=data)
            if service.is_valid():
                print(service)
                service.save()
                rota.save()
                return JsonResponse({'Message': '已完成'}, safe=False)
            else:
                print(service.errors)
                return JsonResponse({'Message': '服务记录生成失败'}, safe=False)
        else:
            print(rota.errors)
            return JsonResponse({'Message': '参数不合法'}, safe=False)


@csrf_exempt
def getFree(request):
    if request.method == "GET":
        allDriver = Driver.objects.filter(WorkingState="在职")
        allCar = Car.objects.filter(WorkingState="可用")
        workingDriver = []
        workingCar = []
        for r in Rota.objects.all():
            workingDriver.append(r.Driver)
            workingCar.append(r.Car)
        freeDriver = set(allDriver).difference(set(workingDriver))
        freeCar = set(allCar).difference(set(workingCar))
        ansD = []
        ansC = []
        for d in freeDriver:
            ansD.append(d.to_dict())
        for c in freeCar:
            ansC.append(c.to_dict())
        return JsonResponse({'Driver': ansD, 'Car': ansC}, safe=False)


@csrf_exempt
def addStation(request):
    if request.method == "POST":
        station = Station.objects.filter(name=request.POST.get("name"))
        if station.exists():
            return JsonResponse({'Message': '站点已存在'}, safe=False)
        else:
            station = StationSerializer(data=request.POST)
            if station.is_valid():
                station.save()
                return JsonResponse({'Message': '成功'}, safe=False)
            else:
                print(station.errors)
                return JsonResponse({'Message': '信息不合法'}, safe=False)


@csrf_exempt
def deleteStation(request):
    if request.method == "POST":
        try:
            station = Station.objects.get(name=request.POST.get("name"))
        except Station.DoesNotExist:
            return JsonResponse({'Message': '站点不存在'}, safe=False)
        isConfirmed = request.POST.get("isConfirmed")
        print(isConfirmed)
        routes = station.route_set.all()
        if isConfirmed is not None or not routes:
            station.delete()
            return JsonResponse({'Message': '成功'}, safe=False)
        else:
            effect = []
            for route in routes:
                effect.append(route.to_dict())
            return JsonResponse({'Message': '失败', 'Routes': effect}, safe=False)


@csrf_exempt
def getStations(request):
    if request.method == "GET":
        st = []
        for s in Station.objects.all():
            st.append(s.to_dict())
        return JsonResponse({'Station': st}, safe=False)


@csrf_exempt
def getService(request):
    if request.method == "GET":
        services = []
        for s in Service.objects.all():
            services.append(s.to_dict())
        return JsonResponse({'Service': services}, safe=False)


@csrf_exempt
def addRecord(request):
    if request.method == "POST":
        try:
            service = Service.objects.get(Car=request.POST.get("Car"),
                                          Driver=request.POST.get("Driver"),
                                          Route=request.POST.get("Route"),
                                          CarSendTime=request.POST.get("CarSendTime"),
                                          CarSendDate=request.POST.get("CarSendDate"))
            print(service.to_dict);
        except Service.DoesNotExist:
            return JsonResponse({'Message': '服务记录不存在'}, safe=False)
        oldDoc = service.to_dict()['Record']
        if oldDoc is not None:
            oldDoc = oldDoc+' \n' + request.POST.get("Reason")
        else:
            oldDoc = request.POST.get("Reason")
        print(oldDoc)
        data = {'Record': oldDoc}
        service = ServiceSerializer(service, data=data)
        if service.is_valid():
            service.save()
            return JsonResponse({'Message': '成功'}, safe=False)
        else:
            print(service.errors)
            return JsonResponse({'Message': '添加服务记录失败'}, safe=False)
